#!/usr/bin/ruby

require 'jira-ruby'
require 'optparse'
require 'parseconfig'

config = ParseConfig.new('/home/uwe/.mylogin')

jira_options = {
  :username     => config['default']['username'],
  :password     => config['default']['password'],
  :site         => 'https://issue.YOURDOMAIN-XYZ.XYZ/', # Adapt this to your need 
  :context_path => '',
  :ssl_verify_mode =>OpenSSL::SSL::VERIFY_NONE,
  :auth_type    => :basic
}

script_options = {}

OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} [options]"

  opts.on('-d', '--debug', 'Debug mode') { |s| script_options[:debug] = true }
  opts.on('-h', '--help', 'Display help') do 
    puts opts
    exit
  end
end.parse!

ARGV.each do |arg| 
  id = arg.sub(/(\w)\s(\d)/, "\\1-\\2")

  # This should be removed. Used to switch between various Jira systems 
  if id.downcase.include?("prosolution") || id.downcase.include?("aracr")
    jira_options[:site] = config['default']['jira_intern']
    A
  elsif id.include?("albatros") || (id.include? "EBACQ") || (id.include? "HAPSD") || (id.include? "STAFFRM")
    jira_options[:site] = config['default']['jira_servicedesk']
  else
    jira_options[:site] = config['default']['jira_extern']
  end

  if script_options[:debug]
    puts "Debug: Site = #{jira_options[:site]}"
  end

  
  client = JIRA::Client.new(jira_options)
  
  # Query ticket and display info
  
  begin
    t = client.Issue.find(id)
  rescue
    fail "Could not find JIRA ticket #{id}. Also check your credentials!"
  end

  puts "#{id}:short_desc:\"#{t.summary}\""
  puts "#{id}:type:\"#{t.issuetype.name}\""
  puts "#{id}:priority:\"#{t.priority.name}\""
  puts "#{id}:status:\"#{t.status.name}\""
  if t.resolution.nil?
    puts "#{id}:resolution:\"\""
  else
    puts "#{id}:resolution:\"#{t.resolution['name']}\""
  end
  puts "#{id}:created:\"#{t.created[0..15]}\""
  puts "#{id}:updated:\"#{t.updated[0..15]}\""
  puts "#{id}:reporter:\"#{t.updated[0..15]}\""
  s = ""
  s = t.assignee.emailAddress if ! t.assignee.nil? 
  puts "#{id}:assignee:\"#{s}\""
  puts "#{id}:url:\"#{jira_options[:site]}browse/#{id}\""
end
